﻿
using InventoryIssue.Domain;
using InventoryIssue.Infrastructrue.Interface;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using SqlSugar;
using System.Data;
using DbType = SqlSugar.DbType;

namespace InventoryIssue.Infrastructrue.Implement
{
    public class DatabaseContext : IDatabaseContext
    {
        private readonly IConfiguration _configuration;
        private readonly string _connectionString;
        public SqlSugarScope SqlSugar { get; }
        public IDbConnection DapperConnection { get; }
        public string apolloconnection {  get; }

        public SqlSugarScope SqlSugarScope => throw new NotImplementedException();

        public DatabaseContext(IConfiguration configuration)
        {
            _connectionString = configuration.GetValue<string>("wmss");
            SqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = _connectionString,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            },
            db =>
            {
                db.DbMaintenance.CreateDatabase("WMSRepository");
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                };
            });
            DapperConnection = new MySqlConnection(_connectionString);
        }


        public void InitializeDatabase()
        {
            try
            {
                
                SqlSugar.CodeFirst.InitTables(

                    //typeof(StocktakingModel),
                    //typeof(AllocateModel),
                    //typeof(StocktakingProductModel)
                    //typeof(AllocateProductModel)
                    //typeof(ReportlossModel),
                    //typeof(ReportlossProductModel)
                    //typeof(OperationLog)
                );

                Console.WriteLine("数据库表初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库初始化失败: {ex.Message}");
                throw; 
            }
        }
    }
}
